package org.tpc.yn.result;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

public class SaResult extends LinkedHashMap<String, Object>  implements Serializable {
    public SaResult() {
    }

    public SaResult(int code, String msg, String data,String sign) {
        this.setCode(code);
        this.setMsg(msg);
        this.setData(data);
        this.setTime(System.currentTimeMillis());
        this.setSign(sign);
    }

    public SaResult(Map<String, ?> map) {
        this.setMap(map);
    }

    public Integer getCode() {
        return (Integer)this.get("code");
    }

    public String getMsg() {
        return (String)this.get("msg");
    }

    public Object getData() {
        return this.get("data");
    }

    public SaResult setCode(int code) {
        this.put("code", code);
        return this;
    }

    public SaResult setMsg(String msg) {
        this.put("msg", msg);
        return this;
    }

    public SaResult setTime(Long times){
        this.put("time", times);
        return this;
    }

    public SaResult setData(String data) {
        this.put("data", data);
        return this;
    }

    public SaResult setSign(String sign){
        this.put("sign", sign);
        return this;
    }

    public SaResult set(String key, Object data) {
        this.put(key, data);
        return this;
    }


    public SaResult setMap(Map<String, ?> map) {
        for(String key : map.keySet()) {
            this.put(key, map.get(key));
        }

        return this;
    }



    public static SaResult ok(String data,String sign) {
        return new SaResult( 1, "成功", data, sign);
    }

    public static SaResult error(String msg){
        return new SaResult( 0, msg, "", "");
    }



    public String toString() {
        return "{\"code\": " + this.getCode() + ", \"msg\": " + this.transValue(this.getMsg()) + ", \"data\": " + this.transValue(this.getData()) + "}";
    }

    private String transValue(Object value) {
        if (value == null) {
            return null;
        } else {
            return value instanceof String ? "\"" + value + "\"" : String.valueOf(value);
        }
    }
}
